/*
 * FileTransfer.java
 *
 * Created on December 5, 2006, 10:36 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package eu.somatik.somaftp.logic;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 *
 * @author francisdb
 */
public class FileTransfer {
    
    private FileInterface fromFile;
    private FileSystemInterface toFileSystem;
    
    private TransferQueueEntry queueEntry;
    
    
    private long startTime;
    
    public FileTransfer(){
        
    }
    
    public void start(){
        if(fromFile.getFileSystem().isConnected() && toFileSystem.isConnected()){
            final Streamer streamer = new Streamer();
            
            startTime = System.currentTimeMillis();
            
            final FileInterface from = fromFile;
            
            new Thread(new Runnable() {
                public void run() {
                    System.out.println("start send");
                    try {
                        from.getFileSystem().send(FileTransfer.this,streamer.out);
                    } catch (FileSystemException ex) {
                        ex.printStackTrace();
                    }
                }
            }).start();
            System.out.println("start rcv "+fromFile.getName());
            try {
                toFileSystem.receive(this, streamer.in);
            } catch (FileSystemException ex) {
                ex.printStackTrace();
            }
        }
        
    }
    
    public void finish(){
        long diff = System.currentTimeMillis() - startTime;
        float sizeKB = (float)fromFile.getSize() / FileSizeFormatter.UNIT;
        float speed = (float)sizeKB / (diff/1000.0f);
        System.out.println("transferred "+fromFile+" at "+ speed +"KB/s");
    }
    
    
    public FileInterface getFromFile() {
        return fromFile;
    }
    
    public void setFromFile(FileInterface fromFile) {
        this.fromFile = fromFile;
    }
    
    public FileSystemInterface getToFileSystem() {
        return toFileSystem;
    }
    
    public void setToFileSystem(FileSystemInterface toFileSystem) {
        this.toFileSystem = toFileSystem;
    }
    
    private class Streamer{
        private PipedInputStream in = new PipedInputStream();
        private PipedOutputStream out = new PipedOutputStream();
        
        private Streamer(){
            try {
                in.connect(out);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        
        public InputStream getIn() {
            return in;
        }
        
        public OutputStream getOut() {
            return out;
        }
        
    }
    
    
    
}
